﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ODS.Utils;
using ODS.WebService.Login_Logout;
using ODS.Config;
using ODS.Model;
using ODS.WebService.DeviceFunctions;
using System.Threading.Tasks;
using ODS.WebService.Registry;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using ODS.UserControls;
using System.Threading;

namespace ODS
{
    public partial class LoginPage : PhoneApplicationPage
    {
        BackgroundWorker backroungWorker;
        Popup myPopup;

        public LoginPage()
        {
            InitializeComponent();

            myPopup = new Popup() { IsOpen = true, Child = new SplashScreen() };
            backroungWorker = new BackgroundWorker();
            RunBackgroundWorker();
        }

        private void RunBackgroundWorker()
        {
            backroungWorker.DoWork += ((s, args) =>
            {
                Thread.Sleep(2000);
            });

            backroungWorker.RunWorkerCompleted += ((s, args) =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    this.myPopup.IsOpen = false;
                    this.UpdateLayout();
                }

                );


            });
            backroungWorker.RunWorkerAsync();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            String username = (String) Setting.Get(Constants.KEY_USERNAME);
            String password = (String)Setting.Get(Constants.KEY_PASSWORD);

            if (username == null || password == null)
            {
                tb_username.MyText = "";
                Password.Password = "";
            }
            else
            {
                tb_username.MyText = username;
                Password.Password = password;
            }

            CheckPasswordWatermark();
        }

        private void PasswordLostFocus(object sender, RoutedEventArgs e)
        {
            CheckPasswordWatermark();
        }

        public void CheckPasswordWatermark()
        {
            var passwordEmpty = string.IsNullOrEmpty(Password.Password);
            PasswordWatermark.Opacity = passwordEmpty ? 100 : 0;
            Password.Opacity = passwordEmpty ? 0 : 100;
        }

        private void PasswordGotFocus(object sender, RoutedEventArgs e)
        {
            PasswordWatermark.Opacity = 0;
            Password.Opacity = 100;
        }

        void showWaiting()
        {
            progressBar_waiting.Visibility = Visibility.Visible;
            btnLogin.IsEnabled = false;
            tb_username.IsEnabled = false;
            Password.IsEnabled = false;
            hlb_createNewAccount.IsEnabled = false;
        }

        void HiddenWaiting()
        {
            progressBar_waiting.Visibility = Visibility.Collapsed;
            btnLogin.IsEnabled = true;
            tb_username.IsEnabled = true;
            Password.IsEnabled = true;
            hlb_createNewAccount.IsEnabled = true;
        }

        private async void btnLogin_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            if (tb_username.MyText == "" || Password.Password == "")
            {
                MessageBox.Show(Constants.MES_USERNAME_OR_PASSWORD_EMPTY,"Warning !",MessageBoxButton.OK);
                return;
            }

            showWaiting();

            InfoResult result = await LoginService.loginService(tb_username.MyText, Password.Password);

            //
            if (result.IsSuccess)
            {
                String message = (String)result.ReturnedObject;

                if (message.Equals(Constants.SUCCESS))
                {
                    //save username and password
                    Setting.Set(Constants.KEY_USERNAME, tb_username.MyText);
                    Setting.Set(Constants.KEY_PASSWORD, Password.Password);

                    if (App.userLogin == null)
                        App.userLogin = new UserAccountModel();
                    App.userLogin.UserLoginName = tb_username.MyText;
                    App.userLogin.UserPassword = Password.Password;

                    await App.MainViewModel.LoadListDeviceFromUser();

                    App.LoadListEventType();
                    
                     //App.MainViewModel.LoadAllMessagesOfUser();

                    this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

                    HiddenWaiting();
                }
                else
                {
                    HiddenWaiting();
                    MessageBox.Show(message);
                }
            }
            else
            {
                HiddenWaiting();
                MessageBox.Show(result.Error);
            }

        }


        private void hlb_createNewAccount_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            this.NavigationService.Navigate(new Uri("/RegisterPage.xaml", UriKind.Relative));
        }
    }
}